<template>
  <div class="other">
    <el-header>
      <template v-if="isExpanded">
        <el-input
          placeholder="请输入单据编号"
          v-model="queryInfo.billNo"
          clearable
          size="small"
          @clear="handleClearBillNo"
        ></el-input>
        <el-date-picker
          v-model="queryInfo.billDate_begin"
          type="date"
          placeholder="请选择开始日期"
          size="small"
          value-format="YYYY-MM-DD"
          @change="handleDateChange"
        ></el-date-picker>
        <span>~</span>
        <el-date-picker
          v-model="queryInfo.billDate_end"
          type="date"
          placeholder="请选择结束日期"
          size="small"
          value-format="YYYY-MM-DD"
          @change="handleDateChange"
        ></el-date-picker>
        <el-input
          placeholder="请输入单据主题"
          v-model="queryInfo.subject"
          clearable
          size="small"
          @clear="handleClearSubject"
        ></el-input>
        <el-select v-model="queryInfo.customerId_dictText" placeholder="请选择客户" size="small">
          <el-option label="请选择客户" value></el-option>
          <el-option label="kunkun" value="customer1"></el-option>
          <!-- 可根据实际情况添加更多客户选项 -->
        </el-select>
        <el-select v-model="queryInfo.billStage" placeholder="请选择单据阶段" size="small">
          <el-option label="请选择单据阶段" value></el-option>
          <el-option label="编制中" value="11"></el-option>
          <el-option label="编制完" value="14"></el-option>
          <el-option label="核批中" value="12"></el-option>
          <el-option label="核批撤销" value="13"></el-option>
          <el-option label="核批完" value="15"></el-option>
          <el-option label="执行中" value="16"></el-option>
          <el-option label="执行止" value="17"></el-option>
          <el-option label="执行完" value="18"></el-option>
        </el-select>
        <el-select v-model="queryInfo.isEffective" placeholder="请选择已生效" size="small">
          <el-option label="请选择已生效" value></el-option>
          <el-option label="是" value="1"></el-option>
          <el-option label="否" value="0"></el-option>
        </el-select>
        <el-select v-model="queryInfo.isClosed" placeholder="请选择已关闭" size="small">
          <el-option label="请选择已关闭" value></el-option>
          <el-option label="是" value="1"></el-option>
          <el-option label="否" value="0"></el-option>
        </el-select>
        <el-select v-model="queryInfo.isVoided" placeholder="请选择已作废" size="small">
          <el-option label="请选择已作废" value></el-option>
          <el-option label="是" value="1"></el-option>
          <el-option label="否" value="0"></el-option>
        </el-select>
      </template>
      <template v-else>
        <el-input
          placeholder="请输入单据编号"
          v-model="queryInfo.billNo"
          clearable
          size="small"
          @clear="handleClearBillNo"
        ></el-input>
        <el-date-picker
          v-model="queryInfo.billDate_begin"
          type="date"
          placeholder="请选择开始日期"
          size="small"
          value-format="YYYY-MM-DD"
          @change="handleDateChange"
        ></el-date-picker>
        <span>~</span>
        <el-date-picker
          v-model="queryInfo.billDate_end"
          type="date"
          placeholder="请选择结束日期"
          value-format="YYYY-MM-DD"
          size="small"
          @change="handleDateChange"
        ></el-date-picker>
      </template>
      <el-button type="primary" size="small" @click="getOtherList()" icon="el-icon-search">查询</el-button>
      <el-button size="small" @click="clear()" plain icon="el-icon-refresh-left">重置</el-button>
      <el-button type="success" size="small" @click="showInit()">新增</el-button>
      <el-button type="info" size="small" @click="excel()">导出EXCEL</el-button>
      <el-button
        type="primary"
        size="small"
        @click="dialogVisible = true"
        icon="el-icon-s-tools"
        plain
      >自定义列</el-button>
      <el-button
        size="small"
        @click="toggleInputExpansion"
        :icon="isExpanded? 'el-icon-s-fold' : 'el-icon-s-unfold'"
      ></el-button>
    </el-header>
    <!-- 自定义列弹窗 -->
    <el-dialog title="自定义列" :visible.sync="dialogVisible">
      <el-checkbox-group v-model="checkedColumns">
        <!-- 绑定列对象，label 为列配置对象 -->
        <el-checkbox v-for="col in allColumns" :key="col.prop" :label="col">{{ col.label }}</el-checkbox>
      </el-checkbox-group>
      <el-button @click="confirmColumns">确定</el-button>
    </el-dialog>

    <el-table :data="otherList" border style="width: 100%">
      <!-- 动态生成普通列（索引列除外） -->
      <template v-for="col in checkedColumns">
        <el-table-column
          v-if="col.prop !== 'index'"
          :key="col.prop"
          :label="col.label"
          :width="columns.find(c => c.prop === col.prop).width"
        >
          <template slot-scope="scope">
            <span v-html="scope.row[col.prop] || '-'"></span>
          </template>
        </el-table-column>
      </template>
      <!-- 单独处理索引列（固定在左侧） -->
      <el-table-column
        v-if="checkedColumns.some(col => col.prop === 'index')"
        type="index"
        fixed
        width="50"
        label="#"
      />
      <!-- 操作列固定在右侧，不参与动态生成 -->
      <el-table-column label="操作" fixed="right" width="150">
        <template slot-scope="scope">
          <el-button size="mini" type="primary" @click="handleEdit(scope.row)">修改</el-button>
          <el-button size="mini" type="danger" @click="handleDelete(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 添加&修改其他管理模态框 -->
     <el-dialog :title="otherId ? '修改其他应收' : '新增其他应收'" :visible.sync="dialogFormVisible">
    <el-form
      :model="otherForm"
      :rules="rules"
      ref="otherForm"
      label-width="100px"
      class="demo-otherForm"
    >
      <el-row>
        <el-col :span="8">
          <el-form-item label="单据编号" prop="billNo" :required="true">
            <el-input v-model="otherForm.billNo"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="单据日期" prop="billDate" :required="true">
            <el-date-picker 
              v-model="otherForm.billDate" 
              type="date" 
              value-format="YYYY-MM-DD"
            ></el-date-picker>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="已生效" prop="isEffective">
            <el-checkbox v-model="otherForm.isEffective"></el-checkbox>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="8">
          <el-form-item label="已关闭" prop="isClosed">
            <el-checkbox v-model="otherForm.isClosed"></el-checkbox>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="已作废" prop="isVoided">
            <el-checkbox v-model="otherForm.isVoided"></el-checkbox>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="生效时间" prop="effectiveTime">
            <el-date-picker 
              v-model="otherForm.effectiveTime" 
              type="datetime" 
              value-format="YYYY-MM-DD HH:mm:ss"
            ></el-date-picker>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="8">
          <el-form-item label="核批人" prop="approver">
            <el-select v-model="otherForm.approver">
              <el-option label="请选择" value=""></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="审批实例" prop="approvalInstance">
            <el-input v-model="otherForm.approvalInstance"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="制单时间" prop="createTime">
            <el-date-picker 
              v-model="otherForm.createTime" 
              type="datetime" 
              value-format="YYYY-MM-DD HH:mm:ss"
            ></el-date-picker>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="8">
          <el-form-item label="制单部门" prop="createDept">
            <el-select v-model="otherForm.createDept">
              <el-option label="请选择" value=""></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="制单人" prop="creator">
            <el-select v-model="otherForm.creator">
              <el-option label="请选择" value=""></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="修改时间" prop="updateTime">
            <el-date-picker 
              v-model="otherForm.updateTime" 
              type="datetime" 
              value-format="YYYY-MM-DD HH:mm:ss"
            ></el-date-picker>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="8">
          <el-form-item label="修改人" prop="updater">
            <el-select v-model="otherForm.updater">
              <el-option label="请选择" value=""></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="自动单据" prop="isAuto">
            <el-select v-model="otherForm.isAuto">
              <el-option label="否" value="否"></el-option>
              <el-option label="是" value="是"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="红字单据" prop="isRubric">
            <el-select v-model="otherForm.isRubric">
              <el-option label="否" value="否"></el-option>
              <el-option label="是" value="是"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="16">
          <el-form-item label="单据主题" prop="subject">
            <el-input v-model="otherForm.subject"></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="8">
          <el-form-item label="业务员" prop="operator">
            <el-input v-model="otherForm.operator" placeholder="请先选择用户">
              <el-button slot="append">选择用户</el-button>
            </el-input>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="业务部门" prop="dept">
            <el-select v-model="otherForm.dept">
              <el-option label="请选择" value=""></el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="8">
          <el-form-item label="客户" prop="customer" :required="true">
            <el-select v-model="otherForm.customer">
              <el-option label="请选择" value=""></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="金额" prop="amount" :required="true">
            <el-input v-model="otherForm.amount" type="number"></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="16">
          <el-form-item label="备注" prop="remark">
            <el-input v-model="otherForm.remark"></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="16">
          <el-form-item label="附件">
            <el-button >点击上传</el-button>
          </el-form-item>
        </el-col>
      </el-row>
      <el-form-item>
        <el-button type="primary" v-if="otherId" @click="editOther('otherForm')">修改</el-button>
        <el-button type="success" v-else @click="addOther('otherForm')">保存</el-button>
        <el-button @click="resetForm('otherForm')">取消</el-button>
        <el-button type="primary" @click="submitOther('otherForm')">提交</el-button>
      </el-form-item>
    </el-form>
  </el-dialog>
    <Pagination
      :page="queryInfo.pageNo"
      :rows="queryInfo.pageSize"
      :componentTotal="otherTotal"
      @changePage="setPage"
      @changeRows="setRows"
    ></Pagination>
  </div>
</template>

<script>
import { exportExcel } from "../../excelOut/excel.js";
import Pagination from "../../../views/pagination/Pagination.vue";
import axios from "axios";
export default {
  components: {
    Pagination
  },
  data() {
    return {
      queryInfo: {
        _t: null,
        isVoided: 0, // 固定值
        billNo: "",
        billDate_begin: "",
        billDate_end: "",
        subject: "",
        customerId_dictText: "",
        billStage: "",
        isEffective: "",
        isClosed: "",
        isVoided: "",
        column: "createTime", // 固定值
        order: "desc", // 固定值
        field:
          "id,,,billNo,billDate,subject,srcNo,customerId_dictText,opDept_dictText,operator_dictText,amt,checkedAmt,billStage_dictText,isEffective_dictText,isClosed_dictText,isVoided_dictText,isAuto_dictText,isRubric_dictText,remark,effectiveTime,approver_dictText,createTime,createBy_dictText,sysOrgCode_dictText,updateTime,updateBy_dictText", // 固定字段
        pageNo: 1, // 固定页码（根据需求调整）
        pageSize: 10 // 固定每页大小（根据需求调整）
      },
      otherList: [],
      otherTotal: 0,
      dialogFormVisible: false,
      otherId: "",
      otherForm: {
        code: "",
        createBy: "",
        createOn: "",
        createUserId: "",
        modifiedBy: "",
        modifiedOn: "",
        modifiedUserId: "",
        name: "",
        remark: "",
        t: null
      },
      rules: {
        billNo: [{ required: true, message: '请输入单据编号', trigger: 'blur' }],
        billDate: [{ required: true, message: '请选择单据日期', trigger: 'change' }],
        customer: [{ required: true, message: '请选择客户', trigger: 'change' }],
        amount: [{ required: true, message: '请输入金额', trigger: 'blur' }]
      },
      checkAll: false,
      isIndeterminate: false,
      columns: [
        { prop: "index", label: "#", type: "index", width: 50 },
        { prop: "billNo", label: "单据编号", width: 180 },
        { prop: "billDate", label: "单据日期", width: 150 },
        { prop: "subject", label: "单据主题", width: 150 },
        { prop: "srcNo", label: "源单号", width: 180 },
        { prop: "customerId_dictText", label: "客户", width: 180 },
        { prop: "opDept_dictText", label: "业务部门", width: 150 },
        { prop: "operator_dictText", label: "业务员", width: 150 },
        { prop: "amt", label: "金额", width: 150 },
        { prop: "checkedAmt", label: "已核销金额", width: 150 },
        { prop: "billStage_dictText", label: "单据阶段", width: 150 },
        { prop: "isEffective_dictText", label: "已生效", width: 100 },
        { prop: "isClosed_dictText", label: "已关闭", width: 100 },
        { prop: "isVoided_dictText", label: "已作废", width: 100 },
        { prop: "isAuto_dictText", label: "自动单据", width: 100 },
        { prop: "isRubric_dictText", label: "红字单据", width: 100 },
        { prop: "remark", label: "备注", width: 150 },
        { prop: "effectiveTime", label: "生效时间", width: 180 },
        { prop: "approver_dictText", label: "核批人", width: 150 },
        { prop: "createTime", label: "制单时间", width: 180 },
        { prop: "createBy_dictText", label: "制单人", width: 150 },
        { prop: "sysOrgCode_dictText", label: "制单部门", width: 150 },
        { prop: "updateTime", label: "修改时间", width: 180 },
        { prop: "updateBy_dictText", label: "修改人", width: 150 }
      ],
      visibleColumns: [], // 实际显示的列
      allColumns: [
        { prop: "index", label: "#", checked: true },
        { prop: "billNo", label: "单据编号", checked: true },
        { prop: "billDate", label: "单据日期", checked: true },
        { prop: "subject", label: "单据主题", checked: true },
        { prop: "srcNo", label: "源单号", checked: true },
        { prop: "customerId_dictText", label: "客户", checked: true },
        { prop: "opDept_dictText", label: "业务部门", checked: true },
        { prop: "operator_dictText", label: "业务员", checked: true },
        { prop: "amt", label: "金额", checked: true },
        { prop: "checkedAmt", label: "已核销金额", checked: true },
        { prop: "billStage_dictText", label: "单据阶段", checked: true },
        { prop: "isEffective_dictText", label: "已生效", checked: true },
        { prop: "isClosed_dictText", label: "已关闭", checked: true },
        { prop: "isVoided_dictText", label: "已作废", checked: true },
        { prop: "isAuto_dictText", label: "自动单据", checked: true },
        { prop: "isRubric_dictText", label: "红字单据", checked: true },
        { prop: "remark", label: "备注", checked: true },
        { prop: "effectiveTime", label: "生效时间", checked: true },
        { prop: "approver_dictText", label: "核批人", checked: true },
        { prop: "createTime", label: "制单时间", checked: true },
        { prop: "createBy_dictText", label: "制单人", checked: true },
        { prop: "sysOrgCode_dictText", label: "制单部门", checked: true },
        { prop: "updateTime", label: "修改时间", checked: true },
        { prop: "updateBy_dictText", label: "修改人", checked: true }
      ],
      dialogVisible: false, // 自定义列弹窗显示控制
      checkedColumns: [],
      isExpanded: false
    };
  },
  computed: {},
  watch: {},
  methods: {
    handleDateChange() {
    },
    // 重新加载数据
    clear() {
      location.reload();
    },
    // 重置单据编号输入框
    handleClearBillNo() {
      this.queryInfo.billNo = "";
    },
    handleClearSubject() {
      this.queryInfo.subject = "";
    },
    // 重置所有查询条件
    handleReset() {
      this.queryInfo.billNo = "";
      this.queryInfo.billDate_begin = "";
      this.queryInfo.billDate_end = "";
      this.queryInfo.subject = "";
      this.queryInfo.customerId_dictText = "";
      this.queryInfo.billStage = "";
      this.queryInfo.isEffective = "";
      this.queryInfo.isClosed = "";
      this.queryInfo.isVoided = "";
    },
    toggleInputExpansion() {
      this.isExpanded = !this.isExpanded;
    },
    confirmColumns() {
      // 无需额外处理，el-checkbox-group 已自动同步 checkedColumns
      this.dialogVisible = false;
    },
    excel() {
      exportExcel(199, this, "其他应收数据");
    },
    showInit() {
      this.dialogFormVisible = true;
      this.otherId = "";
      this.otherForm = {
        code: "",
        name: "",
        remark: ""
      };
    },
    // 获取列表
    async getOtherList() {
      const token = localStorage.getItem("token");
      const getOtherListData = async queryInfo => {
        const currentTime = Date.now();
        this.queryInfo._t = currentTime;

        const queryParams = new URLSearchParams(queryInfo).toString();
        const url = `http://api.erp.byesame.com/jeecg-boot/finance/finReceivable/list/199?${queryParams}`;

        try {
          const response = await axios.get(url, {
            headers: {
              "x-access-token": token
            }
          });
          return response;
        } catch (error) {
          console.error("请求出错:", error);
          throw error;
        }
      };

      try {
        const { data: res } = await getOtherListData(this.queryInfo);
        this.otherList = res.result.records.map(item => ({
          ...item,
          checked: false
        }));
        this.otherTotal = res.result.total;
        this.updateCheckStatus();
      } catch (error) {
        console.error("请求出错:", error);
      }
    },
    // 假设分页组件传递当前页和每页大小
    setRows(val) {
      this.queryInfo.pageSize = val;
      this.getOtherList();
    },
    setPage(val) {
      this.queryInfo.pageNo = val;
      this.getOtherList();
    },
    // 添加其他管理
    async addOther(formName) {
      this.$refs[formName].validate(async valid => {
        if (!valid) return false;
        const addOther = async formData => {
          const token = localStorage.getItem("token");
          const url = "http://8.142.74.15:9091/api/biosample/other/save";
          try {
            const response = await axios.post(url, formData, {
              headers: {
                "x-access-token": token
              }
            });
            return response;
          } catch (error) {
            console.error("请求出错:", error);
            throw error;
          }
        };
        try {
          const { data: res } = await addOther(this.otherForm);
          this.$message.success("添加其他管理成功");
          this.dialogFormVisible = false;
          this.getOtherList();
        } catch (error) {
          console.error("添加其他时出错:", error);
        }
      });
    },
    // 重置表单
    resetForm(formName) {
      this.$refs[formName].resetFields();
    },
    // 修改按钮打开模态框事件
    async handleEdit(row) {
      this.dialogFormVisible = true;
      this.otherId = row.id;
      const t = Date.now();
      const token = localStorage.getItem("token");
      const url = `http://8.142.74.15:9091/api/biosample/other/info/${this.otherId}?t=${t}`;
      try {
        const { data: res } = await axios.get(url, {
          headers: {
            "x-access-token": token
          }
        });
        this.otherForm = res.other;
        this.$message.success("打开编辑页面成功");
      } catch (error) {
        console.error("打开编辑页面出错:", error);
        this.$message.error("打开编辑页面出错");
      }
    },
    // 修改按钮提交表单事件
    editForm(formName) {
      this.$refs[formName].validate(async valid => {
        if (!valid) return false;
        const editOther = async formData => {
          const token = localStorage.getItem("token");
          const url = "http://8.142.74.15:9091/api/biosample/other/update";
          try {
            const response = await axios.post(url, formData, {
              headers: {
                "x-access-token": token
              }
            });
            return response;
          } catch (error) {
            console.error("请求出错:", error);
            throw error;
          }
        };
        try {
          const { data: res } = await editOther(this.otherForm);
          if (res.code != 0) return this.$message.error("编辑其他管理失败");
          this.$message.success("编辑其他管理成功");
          this.dialogFormVisible = false;
          this.getOtherList();
        } catch (error) {
          console.error("添加其他管理时出错:", error);
        }
      });
    },
    // 删除其他管理
    handleDelete(row) {
      this.$confirm("是否删除该数据?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          this.deleteTeam(row);
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除"
          });
        });
    },
    async deleteTeam(row) {
      const token = localStorage.getItem("token");
      const url = "http://8.142.74.15:9091/api/biosample/other/delete";
      try {
        const res = await axios.post(url, [row.id], {
          headers: {
            "x-access-token": token
          }
        });
        this.$message.success("删除其他成功");
        this.getOtherList();
      } catch (error) {
        console.error("删除其他时出错:", error);
        this.$message.error("删除其他时出错");
      }
    },
    handleCheckAllChange(val) {
      this.otherList.forEach(item => {
        item.checked = val;
      });
      this.updateCheckStatus();
    },
    handleSingleCheckChange() {
      const checkedCount = this.otherList.filter(item => item.checked).length;
      this.checkAll = checkedCount === this.otherList.length;
      this.isIndeterminate =
        checkedCount > 0 && checkedCount < this.otherList.length;
    },
    updateCheckStatus() {
      const checkedCount = this.otherList.filter(item => item.checked).length;
      this.checkAll = checkedCount === this.otherList.length;
      this.isIndeterminate =
        checkedCount > 0 && checkedCount < this.otherList.length;
    },
    async allDetele() {
      const checkedIds = this.otherList
        .filter(item => item.checked)
        .map(item => item.id);
      if (checkedIds.length === 0) {
        return this.$message.warning("请选择要删除的其他");
      }

      // 添加确认弹出框
      await this.$confirm(
        `确定删除选中的 ${checkedIds.length} 条其他？`,
        "删除确认",
        {
          confirmButtonText: "删除",
          cancelButtonText: "取消",
          type: "warning"
        }
      )
        .then(async () => {
          // 使用async处理await
          const token = localStorage.getItem("token");
          const url = "http://8.142.74.15:9091/api/biosample/other/delete";
          try {
            const res = await axios.post(url, checkedIds, {
              headers: {
                "x-access-token": token
              }
            });
            this.$message.success(`成功删除 ${checkedIds.length} 条其他`);
            this.getOtherList();
          } catch (error) {
            console.error("批量删除其他时出错:", error);
            this.$message.error(
              `删除失败：${error.response?.data?.msg || "网络错误"}`
            );
          }
        })
        .catch(() => {
          this.$message.info("已取消删除操作");
        });
    }
  },
  created() {
    // 初始化可见列（根据 allColumns 中 checked 为 true 的列）
    this.checkedColumns = this.allColumns.filter(col => col.checked);
  },
  mounted() {
    this.getOtherList();
  }
};
</script>

<style lang="scss" scoped>
html,
body {
  height: 100%;
}
.other {
  height: 100%;
  padding: 20px;
  .el-header {
    height: 32px !important;
    padding: 0;
    display: flex;
    .el-button {
      margin-left: 10px;
    }
    .el-input {
      width: 360px;
    }
  }
  .el-table {
    margin-top: 20px;
    height: 100%;
    overflow: auto;
  }
}
</style>  